#include<bits/stdc++.h>
#define int long long
using namespace std;
inline int read(){
	int x=0;bool f=0;char ch=getchar();
	while(ch<'0'||ch>'9')f^=(ch=='-'),ch=getchar();
	while('0'<=ch&&ch<='9')x=(x<<1)+(x<<3)+(ch^48),ch=getchar();
	return f?-x:x;
}
const int Maxn=1e5+5,N=1e7+5;
int n,m;
struct edge{int u,v,w;}e[N];
inline bool cmp(edge a,edge b){
	return a.w<b.w;
}
int pd[3005][3005];
int f[Maxn];
int find(int x){return f[x]==x?x:f[x]=find(f[x]);}
signed main(){
//	ios::sync_with_stdio(0);
//	cin.tie(0);cout.tie(0);
	freopen("up.in","r",stdin);
	freopen("up.out","w",stdout);
	int T=read();
	while(T--){
		n=read();m=read();
		for(int i=1;i<=n;i++)
			for(int j=1;j<=n;j++)
				pd[i][j]=0;
		for(int i=1;i<=m;i++){
			e[i]={read(),read(),read()};
			pd[e[i].u][e[i].v]=1;
			pd[e[i].v][e[i].u]=1;
		}int cnt=m;
		if(!m){
			printf("%lld\n",n-1);
			continue;
		}
		for(int i=1;i<=n;i++)
			for(int j=i+1;j<=n;j++){
				if(!pd[i][j])e[++cnt]={i,j,j-i};
			}
		sort(e+1,e+1+cnt,cmp);
		for(int i=1;i<=n;i++)f[i]=i;
		int ans=0;
		for(int i=1;i<=cnt;i++){
			if(find(e[i].u)!=find(e[i].v)){
				f[find(e[i].u)]=find(e[i].v);
				ans+=e[i].w;
			}
		}printf("%lld\n",ans);
	}
	return 0;
}

